﻿using TianYuan.AutoMapper;
using TianYuan.Core.Application.Services;
using TianYuan.Core.Caching;
using TianYuan.Core.Domain.Uow.Interception;
using TianYuan.Data.Dapper.Repositories;
using TianYuan.Data.Dapper.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TianYuan.Utils.Extensions;
using TianYuan.Data.Dapper;
using System.Diagnostics;

namespace Domain
{
    public class ProductAppService :  IProductAppService
    {
        private readonly IProductRepository _productRepository;
        private readonly IUnitOfWork _Uow;
        public ProductAppService(IProductRepository productRepository,
            IUnitOfWork uow)
        {
            _productRepository = productRepository;
            
            _Uow = uow;
        }
        [Transactional]
        public bool Add(ProductDto dto)
        {
            /**
             * 
             *  var result = new DbResult<T>();
            try
            {
                this.BeginTran();
                if (action != null)
                    result.Data = action();
                this.CommitTran();
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.ErrorException = ex;
                result.ErrorMessage = ex.Message;
                result.IsSuccess = false;
                this.RollbackTran();
            }
            return result;
             * */
            // var result = _Uow.Currentontext.Ado.UseTran<bool>(() =>
            //{
            //    Product p = dto.MapTo<Product>();
            //    var v = _Repository.Insert(p) != null;
            //    GetProducts();
            //    return v;

            //});
            // return result.Data;
            //_Uow.BeginTransaction();
            try
            {

                Product p = dto.MapTo<Product>();
                var v = _productRepository.Insert(p);
                //GetProducts();
                //_productRepository.Query();
                //_Uow.Commit();
                throw new Exception();
                return v;
                //var v= !string.IsNullOrEmpty((string)_productRepository.Insert(product));
            }
            catch (Exception)
            {

                throw;
            }
        }
        
        public void TestFilters()
        {
            var list = _productRepository.ContextInstance().Queryable<Product>().ToSql();
            Console.WriteLine("");
        }
        public List<Product> GetProducts()
        {
            //List<Product> list = Getlist();
            //return list;
            ICache cache = CacheManager.GetCacher<List<Product>>();
            const string key = "KEY__fdsaf";

            var v = cache.Get<List<Product>>(key, Getlist, 3600);
            return v;
        }
        [Caching(CachingMethod.Get, 120, key: "methodname+#args[0]")]
        public List<ProductResultDto> GetTestCache0(string id)
        {
            var list = _productRepository.ContextInstance().Queryable<Product>().ToSql();
            //foreach (ProductResultDto item in list)
            //{
            //    item.Dt1 = DateTime.Now;
            //}
            return new List<ProductResultDto>();
        }
        //[Caching(CachingMethod.Get, 120,key: "#query.Name")]
        [Caching(CachingMethod.Get, 12000)]
        public List<ProductResultDto> GetTestCache(ProductQueryDto query)
        {
            var list= _productRepository.ContextInstance().Queryable<Product>().ToSql();
            //foreach (ProductResultDto item in list)
            //{
            //    item.Dt1 = DateTime.Now;
            //}
            ProductResultDto dto = new ProductResultDto { Id = "11111", Name = "曾繁林" };
            return new List<ProductResultDto>() { dto };
        }
        [Caching(CachingMethod.Remove, 120,"","",new Type[] { typeof(List<ProductResultDto>) })]
        public void ClearCache(ProductQueryDto query)
        {
            Debug.Print("啦啦啦啦");
        }
        private List<Product> Getlist()
        {
            /**
             * for (int i = 0; i < 10000; i++)
            {
                db.Queryable<Student>().Where(it => it.Id > 0).WithCache().ToList();
            }


            db.Queryable<Student, Student>((s1, s2) => s1.Id == s2.Id).Select(s1 => s1).WithCache().ToList();


            db.Queryable<Student, Student>((s1, s2) => new object[] {
                JoinType.Left,s1.Id==s2.Id
            }).Select(s1 => s1).WithCache().ToList();


            Console.WriteLine("Cache Key Count:" + myCache.GetAllKey<string>().Count());

            foreach (var item in myCache.GetAllKey<string>())
            {
                Console.WriteLine();
                Console.WriteLine(item);
                Console.WriteLine();
            }

            db.Deleteable<Student>().Where(it => it.Id == 1).RemoveDataCache().ExecuteCommand();
             * 
             * */

            return _productRepository.ContextInstance().Queryable<Product>().ToList();//缓存30s
            //_productRepository.GetAll().ToList();
        }
    }
}
